package CompletableFuturefd.bachCF;

import com.google.common.collect.Lists;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BatchProcessingEx2 {

    private static final ExecutorService executor = Executors.newFixedThreadPool(10);

    public static void main(String[] args) {
        System.out.println("===开始========");
        List<Integer> items = getItems(); // 假设这是一个获取待处理数据的方法
        // 分批处理
        List<List<Integer>> batches = Lists.partition(items, 10);
        List<CompletableFuture<Void>> futures = new ArrayList<>(batches.size());
        batches.forEach(batch ->{
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                // 处理每个批次的数据
                batch.forEach(item -> {
                    // 实际的处理逻辑
                    System.out.println("Processing item: " + item);
                });
            }, executor);
            futures.add(future);
        });
        // 等待所有批次处理完成
        CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
        System.out.println("===结束========");
        // 关闭executor服务，防止资源泄露
        executor.shutdown();
    }



    private static List<Integer> getItems() {
        List<Integer> list = new ArrayList<>();
        for (int i = 1; i <=100; i++) {
            list.add(i);
        }
        return list;
    }
}